import os
from dotenv import load_dotenv
from flask import Flask
from flask_cors import CORS
from extensions import db, redis_store
from blueprints.dongchedi import dongchedi_bp
from blueprints.fxbaogao import fxbaogao_bp
from blueprints.qqnews import qqnews_bp
from blueprints.sspai import sspai_bp
from blueprints.thepaper import thepaper_bp
from blueprints.xfz import xfz_bp
from blueprints.zhihu import zhihu_bp
from blueprints.douyin import douyin_bp
from blueprints.ithome import ithome_bp
from blueprints.user import user_bp
from blueprints.weibo import weibo_bp
from blueprints.baidutieba import baidutieba_bp
from blueprints.kr36 import kr36_bp
from models.hotspot import Hotspot
from models.user import User
from tasks.scheduler import init_scheduler

# 加载环境变量
load_dotenv()

app=Flask(__name__)
CORS(
    app,
    resources={
        r"/*": {
            "origins": ["http://localhost:5173"],
            "supports_credentials": True,
            "allow_headers": ["Content-Type", "Authorization"],
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        }
    },
)

app.secret_key = os.getenv("SECRET_KEY")

# 配置数据库连接信息
app.config.from_object('config')
db.init_app(app)
redis_store.init_app(app)


app.register_blueprint(dongchedi_bp)
app.register_blueprint(fxbaogao_bp)
app.register_blueprint(qqnews_bp)
app.register_blueprint(sspai_bp)
app.register_blueprint(thepaper_bp)
app.register_blueprint(xfz_bp)
app.register_blueprint(zhihu_bp)
app.register_blueprint(douyin_bp)
app.register_blueprint(ithome_bp)
app.register_blueprint(user_bp)
app.register_blueprint(weibo_bp)
app.register_blueprint(baidutieba_bp)
app.register_blueprint(kr36_bp)
with app.app_context():
    # 创建数据库表
    db.create_all()

# 初始化定时任务
init_scheduler(app)

@app.errorhandler(Exception)
def handle_exception(e):
    """全局异常处理"""
    print("发生异常:", e)
    return {"msg": "服务器错误", "success": False, "data": None}, 500

if __name__=='__main__':
    # app.debug = True  # 开启调试模式
    app.run()